<script setup lang="ts">
import { ref, computed } from "vue";
import { validPhone } from "@/utils/validate";
import { sendSms } from "@/api/user/login";
const sms = ref("");
const timeSize = ref<number>(60);
const codeTimer = ref();
const isOne = ref<boolean>(false);
const loading = ref<boolean>(false);
const props = defineProps({
  modelValue: String,
  phone: String || Number,
});
const emits = defineEmits(["update:modelValue"]);

const code = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  },
});
const isDisible = computed(() => {
  return !validPhone(props.phone) || timeSize.value!==60;
});

function handleTimer() {
  codeTimer.value = setInterval(() => {
    if (timeSize.value > 0) {
      timeSize.value--;
    } else {
      timeSize.value = 60;
      clearInterval(codeTimer.value);
    }
  }, 1000);
}

function handleCode() {
  loading.value = true;
  if (!props.phone) return;
  const obj = {
    phone: props.phone,
  };
  sendSms(obj)
    .then(() => {
      loading.value = false;
      timeSize.value--;
      if (!isOne.value) isOne.value = true;
      handleTimer();
    })
    .catch((err) => {
      loading.value = false;
    });
}
</script>

<template>
  <div>
    <uni-easyinput class="uni-mt-5" trim="all" v-model="code" placeholder="请输入验证码">
      <template #right>
        <button
          :loading="loading"
          @click="handleCode"
          size="mini"
          class="code-button"
          plain
          :disabled="isDisible"
          hairline
        >
          {{ timeSize != 60 ? timeSize + "秒后重发" : isOne ? "重新发送" : "发送验证码" }}
        </button>
      </template>
    </uni-easyinput>
  </div>
</template>

<style lang="scss" scoped>
.code-button {
  border: none;
  background-color: transparent !important;
  font-size: 12px;
  color: #666;
}
</style>
